package thesis.filesharing.services.fulltextsearch.indexing;

import thesis.filesharing.common.exception.functional.InvalidArgumentException;

public class QueryBuilder {
	
	private StringBuilder builder = new StringBuilder();
	
	public String buildQuery() {
		return builder.toString();
	}
	
	public QueryBuilder add(String param, String value, Operators operator) {
		builder.append(buildExpression(param, value, operator));
		return this;
	}
	
	public QueryBuilder and(String param, String value, Operators operator) {
		if ("".equals(builder.toString().trim())) {
			builder.append(buildExpression(param, value, operator));
		} else {
			builder.append(" AND ").append(buildExpression(param, value, operator));
		}
		return this;
	}
	
	public QueryBuilder or(String param, String value, Operators operator) {
		if ("".equals(builder.toString().trim())) {
			builder.append(buildExpression(param, value, operator));
		} else {
			builder.append(" OR ").append(buildExpression(param, value, operator));
		}
		return this;
	}
	
	public QueryBuilder and(QueryBuilder queryBuilder) {
		if ("".equals(builder.toString().trim()) && "".equals(queryBuilder.builder.toString().trim())) {
			throw new InvalidArgumentException();
		} else if ("".equals(builder.toString().trim())) {
			return queryBuilder;
		} else if ("".equals(queryBuilder.builder.toString().trim())) {
			return this;
		} else {
			builder.insert(0, "(").append(") AND (").append(queryBuilder.builder).append(")");
			return this;
		}
	}
	
	public QueryBuilder or(QueryBuilder queryBuilder) {
		if ("".equals(builder.toString().trim()) && "".equals(queryBuilder.builder.toString().trim())) {
			throw new InvalidArgumentException();
		} else if ("".equals(builder.toString().trim())) {
			return queryBuilder;
		} else if ("".equals(queryBuilder.builder.toString().trim())) {
			return this;
		} else {
			builder.insert(0, "(").append(") OR (").append(queryBuilder.builder).append(")");
			return this;
		}
	}
	
	public QueryBuilder not() {
		if ("".equals(builder.toString().trim())) {
			throw new InvalidArgumentException();
		} else {
			builder.insert(0, "NOT(").append(")");
			return this;
		}
	}
	
	private String buildExpression(String param, String value, Operators operator) {
		StringBuilder b = new StringBuilder();
		if (operator == Operators.COLON && value.trim().split(" ").length > 1) {
			b.append(param).append(operator.getOperator()).append("\"").append(value).append("\"");
		} else {
			b.append(param).append(operator.getOperator()).append(value);
		}
		return b.toString();
	}
}
